package com.yonyou.ucf.mdf.app.util;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class TenantClearRSAUtils {

    private static final String RSA_ALGORITHM = "RSA";

    private static final String publicKeyString = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANTodIeOZuk2hobvIN107UEnMBPR+fbF"
            + "OqcGm4EF0QxIxGg1thPBNTp3c68iW1qapZmG7kJj31YK7zqpO2oifOkCAwEAAQ==";

    private static final String privateKeyString = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA1Oh0h45m6TaGhu8g"
            + "3XTtQScwE9H59sU6pwabgQXRDEjEaDW2E8E1OndzryJbWpqlmYbuQmPfVgrvOqk7"
            + "aiJ86QIDAQABAkBjOwh82ZkLXxdqMm+9565grHQS+M2o/xmsGT9G7kAVmcalyv3l"
            + "s9rOINFtugdOkYsJg/IWyS7cyg+2EAI7jAsVAiEA+PnvekKoo1jLGMzw12zH1EDm"
            + "YDBj4qJQ3Gdvmy79OV8CIQDa6gpty7NdNORi3+KBs/heSCq4Z8cqlrQtbPQCnKHG"
            + "twIgLTsquGlXvaUp8G1664gFnZfUwnDIFKosSn44FlcpBb0CIQDPAmQMQYUCTaLu"
            + "kNHrXtktpsanDJO9BTeqgQ4Zbi5Y7wIhAJCGtJDRNicEVomT5wk/yeBBr2s16r+/"
            + "U6g8KQZBeIhh";

    public static String encrypt(String plaintext) throws Exception {
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);

        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String cipherText) throws Exception {
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyString);

        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] encryptedBytes = Base64.getDecoder().decode(cipherText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    /**
     * 判断是否需要忽略安全拦截的请求（目前主要是openAPI、内部请求）
     * @return
     */
    public static boolean isFromInnerReq(HttpServletRequest request){
        //判断是否内网请求
        boolean isFromInner = false;
        String netWorkType = request.getHeader("x-network-type");
        if (StringUtils.isNotEmpty(netWorkType) && !netWorkType.equalsIgnoreCase("public")) {
            isFromInner = true;
        }

        return isFromInner;
    }

//    public static void main(String[] args) throws Exception {
//        String tenantId = "11238139";
//        String ciphertext = TenantClearRSAUtils.encrypt(tenantId);
//        String decryptedText = TenantClearRSAUtils.decrypt(ciphertext);
//
//        System.out.println("tenantId: " + tenantId);
//        System.out.println("Ciphertext: " + ciphertext);
//        System.out.println("Decrypted Text: " + decryptedText);
//    }
}
